package com.caocaog.market.merchant.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.merchant.entity.MkMerchantBasic;
import com.caocaog.market.merchant.service.MkMerchantService;
import com.caocaog.market.merchant.vo.MerchantCreateVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SystemSite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.util.List;

/**
 * @author liguang
 * @version 1.0.0
 * @Project jeecg-boot
 * @Package com.caocaog.market.merchant.controller
 * @ClassName CertificationController.java
 * @createTime 2021年11月29日 11:19:00
 * @Description 商家实名认证所用到的信息
 */
@Api(tags = "商家实名认证")
@RestController
@RequestMapping("/merchant/certification")
@Slf4j
@SuppressWarnings("all")
public class CertificationController {
    @Autowired
    private CommonAPI commonAPI;

    @Autowired
    private MkMerchantService merchantService;
    /** 系统中所有的分站信息列表 */
    @AutoLog(value = "商家实名认证-查询系统中所有分站列表")
    @RequestMapping("/allSite")
    @ApiOperation(value = "商家实名认证-查询系统中所有分站列表", notes = "商家实名认证-查询系统中所有分站列表")
    public Result allSite(){
        List<SystemSite> sites = commonAPI.findAllSystemSite();
        Result result = new Result();
        result.setResult(sites);
        return result;
    }


    /**
     * 根据当前用户查询当前登录用户的商家信息
     * @param merchant
     * @return
     */
    @AutoLog(value = "商家实名认证-根据当前登录用户查询当前当前登录用户提交的商家实名认证信息")
    @ApiOperation(value = "商家实名认证-根据当前登录用户查询当前当前登录用户提交的商家实名认证信息", notes = "商家实名认证-根据当前登录用户查询当前当前登录用户提交的商家实名认证信息")
    @GetMapping("/findByUserId")
    public Result findMerchantByUserId(){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Result relt = new Result();
        try{
            relt.setResult(merchantService.findByUserId(loginUser.getId()));
            relt.setSuccess(true);
        }catch (Exception e){
            relt.error500("查询出错！");
        }
        return relt;
    }

    @AutoLog(value = "商家信息-根据商家id获取商家信息")
    @ApiOperation(value = "商家信息-根据商家id获取商家信息", notes = "商家信息-根据商家id获取商家信息")
    @GetMapping("/findMerchantById")
    public Result findMerchantById(String merchantId){
        Result relt = new Result();
        try{
            relt.setResult(merchantService.findMerchantById(merchantId));
            relt.setSuccess(true);
        }catch (Exception e){
            relt.error500("查询出错！");
        }
        return relt;
    }


    @AutoLog(value = "商家实名认证-保存用户提交的商家实名认证信息")
    @PostMapping("/edit")
    @ApiOperation(value = "商家实名认证-保存用户提交的商家实名认证信息", notes = "商家实名认证-保存用户提交的商家实名认证信息")
    public Result edit(@RequestBody MkMerchantBasic merchant){
        // 查询当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Result relt = new Result();
        relt = validMerchant(merchant,relt);
        if(!relt.isSuccess()){
            return relt;
        }
        int count = merchantService.insertOrUpdMkMerchant(merchant);
        /**
         * 当用户的realname为空，或realname不为空 且 realname不等于merchang.getName()时
         *      才会执行用户名更新
         */
        String userRealName = loginUser.getRealname();
        if(StringUtils.isBlank(userRealName) || (StringUtils.isNotBlank(userRealName) && !userRealName.equals(merchant.getName()))){
            // 提交或修改实名信息后更改用户名
            merchantService.updateRealnameByUserId(loginUser.getId(),merchant.getName());
        }
        relt.setSuccess(count>0?true:false);
        relt.success("提交成功！");

        return relt;
    }
    @GetMapping("/merchantList")
    @ApiOperation(value = "商家列表——查询当前登录分站下所有的商家", notes = "商家列表——查询当前登录分站下所有的商家")
    public Result findAllMerchant(MkMerchantBasic merchant,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="100") Integer pageSize, HttpServletRequest req){

        Result<IPage<MkMerchantBasic>> result = new Result<IPage<MkMerchantBasic>>();
        Page<MkMerchantBasic> page = new Page<MkMerchantBasic>(pageNo, pageSize);
        IPage<MkMerchantBasic> pageList = merchantService.findMerchantList(page,merchant);
        log.info("查询当前页："+pageList.getCurrent());
        log.info("查询当前页数量："+pageList.getSize());
        log.info("查询结果数量："+pageList.getRecords().size());
        log.info("数据总数："+pageList.getTotal());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }
    @GetMapping("/merchantAllList")
    @ApiOperation(value = "商家列表——根据分站id查询该分站下所有的商家", notes = "商家列表——根据分站id查询该分站下所有的商家")
    public Result merchantAllList(MkMerchantBasic merchant,HttpServletRequest req){
        Result<List<MkMerchantBasic>> result = new Result<List<MkMerchantBasic>>();
        List<MkMerchantBasic> merchantList = merchantService.findMerchantListNoPage(merchant);
        result.setSuccess(true);
        result.setResult(merchantList);
        return result;
    }
    @AutoLog(value = "商家实名认证-分站审核")
    @PostMapping("/check")
    @ApiOperation(value = "商家列表——审核商家实名认证信息", notes = "商家列表——审核商家实名认证信息")
    public Result check(@RequestBody MkMerchantBasic basic,HttpServletRequest req){
        Result relt = new Result();
        if(null==basic){
            relt.error500("请填写审核信息！");
            return relt;
        }
        Integer state = basic.getState();
        if(null==state || state== MarketConstant.MERCHANT_CHECK_DSH){
            relt.error500("请选择除“待审核”以外的审核结果！");
            return relt;
        }
        if(!state.equals(MarketConstant.MERCHANT_CHECK_TH)){
            if(StringUtils.isBlank(basic.getType())){
                relt.error500("请选择类型");
                return relt;
            }
            if(state.equals(MarketConstant.MERCHANT_CHECK_SHTG) && null==basic.getGrade()){
                // 审核通过时，必须要选择等级
                relt.error500("请选择等级");
                return relt;
            }
            if(state==MarketConstant.MERCHANT_CHECK_BTG && StringUtils.isBlank(basic.getCheckFailReason())){
                // 只有审核不通过时，才会要求填写审核不通过的原因
                relt.error500("请填写审核不通过的原因");
                return relt;
            }else{
                basic.setCheckFailReason(MarketConstant.MERCHANT_CHECK_BTG.equals(state)?basic.getCheckFailReason():null);
            }
        }
         relt.setSuccess(merchantService.checkMerchant(basic)>0?true:false);
        return relt;
    }


    private Result validMerchant(MkMerchantBasic merchant,Result relt){
        boolean flag = true;
        String message="";
        if(null==merchant){
            flag = false;
            message = "必要的参数不能为空！";
        }
        // 验证商家手机号是否重复
        if(StringUtils.isNotBlank(merchant.getMobile())){
            if(merchantService.findCountByMobile(merchant.getMobile(),merchant.getId())>0){
                flag = false;
                message = "您所用的手机号已注册成为商家，不可重复注册，如有问题请联系客服处理！";
                relt.setSuccess(flag);
                relt.setMessage(message);
                return relt;
            }
        }
        if(StringUtils.isBlank(merchant.getName())){
            flag = false;
            message = "姓名不能为空！";
        }
        if(StringUtils.isBlank(merchant.getSiteId())){
            flag = false;
            message = "分站不能为空！";
        }
        if(StringUtils.isBlank(merchant.getIdcard())){
            flag = false;
            message = "身份证件号码不能为空！";
        }
        if(StringUtils.isBlank(merchant.getType())){
            flag = false;
            message = "类型不能为空！";
        }
        if(StringUtils.isBlank(merchant.getAliname())){
            flag = false;
            message = "提现人支付宝姓名不能为空！";
        }
        if(StringUtils.isBlank(merchant.getAlipay())){
            flag = false;
            message = "提现人支付宝账号不能为空！";
        }
        // 验证身份证号是否重复
        List<MkMerchantBasic> basics = merchantService.validIdcard(merchant.getIdcard(),merchant.getId());
        if(null!=basics && basics.size()>0){
            // 有重复
            flag = false;
            message = "身份证号不允许重复！";
        }
        relt.setSuccess(flag);
        relt.setMessage(message);
        return relt;
    }




}
